#!/bin/bash
#description: Nginx start-stop script.
# by oilive
#nginx路径
nginx_url=/usr/local/nginx/

#判断是否存在进程
judge(){
	num=`ps -ef |grep nginx |grep -v grep |grep process |wc -l`
	if [ ${num} -eq 0 ];then
		return 0
	else
		return 1
	fi
}
start(){
	if judge;then
		cd ${nginx_url}sbin/
		./nginx -c ${nginx_url}conf/nginx.conf
		echo -e "\033[31mnginx\033[0m \033[33mstart\033[0m \033[32msuccessfully\033[0m!!!"
	else
		echo -e "\033[31mnginx\033[0m is \033[32mrunning\033[0m, so \033[33mno\033[0m need \033[31mstart\033[0m!!!" 
	fi
}
stop(){
	if judge;then
		echo -e "\033[31mnginx\033[0m \033[33mnot start\033[0m, so \033[33mno\033[0m need \033[31mstop\033[0m!!!" 
	else
		PID=`ps -ef|grep nginx|grep process|awk '{print $2}'`
		kill -9 $PID
		echo -e "\033[31mnginx\033[0m \033[33mstop\033[0m \033[32msuccessfully\033[0m!!!"
	fi
}
proc(){
	if judge;then
		echo -e "\033[31mnginx\033[0m \033[33mnot start\033[0m, so \033[33mdoesn't\033[0m have \033[31mnginx\033[0m \033[34mprocess\033[0m!!!" 
	else
		echo -e "\033[31mnginx\033[0m is \033[32mrunning\033[0m, \033[34mSee next line for process content\033[0m!!!"
		ps -ef | grep nginx | grep process
	fi
}
#日志存储路径
logs_backup_path="logs_backup/$year$month"
#要切割的日志路径
logs_path="logs/"
#要切割的日志
logs_access="access"
logs_error="error"
#nginx的pid
pid="logs/nginx.pid"
maxsize=$((1024*1024*100))
rq=`date +%Y%m%d`

function backUp(){
	[ -d $nginx_url$logs_backup_path ]|| mkdir -p $nginx_url$logs_backup_path
	filesize=`ls -l ${nginx_url}${logs_path}${logs_access}.log | awk '{ print $5}'`
	if [ $filesize -gt $maxsize ] ;then
		mv ${nginx_url}${logs_path}${logs_error}.log ${nginx_url}${logs_backup_path}/${logs_error}_${rq}.log
		mv ${nginx_url}${logs_path}${logs_access}.log ${nginx_url}${logs_backup_path}/${logs_access}_${rq}.log
		#向nginx主进程发信号重新打开日志
		kill -USR1 `cat ${nginx_url}${pid_path}`
	else
		echo "access.log文件未超过${maxsize}M大小，不进行备份"
	fi
}
#使用说明，用来提示输入参数
usage() {
    echo "请使用: $0 [start|stop|restart|ps|access|error|catconf|vimconf|backup]来运行"
    exit 1
}
case "$1" in
	'start')
		start
	;;
	'stop')
		stop
	;;
	'restart')
		stop
		start
		proc
	;;
	'ps')
		proc
	;;
	'access')
		tail -100f ${nginx_url}logs/access.log
	;;
	'error')
		tail -100f ${nginx_url}logs/error.log
	;;
	'catconf')
		cat ${nginx_url}conf/nginx.conf
	;;
	'vimconf')
		cp ${nginx_url}conf/nginx.conf ${nginx_url}conf/nginx.conf_$rq
		echo "${nginx_url}conf/nginx.conf文件已备份,备份文件为：${nginx_url}conf/nginx.conf_$rq"
		vim ${nginx_url}conf/nginx.conf
	;;
	'backup')
		backUp
	;;
	*)
		usage
	;;
esac